package config

import (
	"github.com/nacos-group/nacos-sdk-go/v2/clients"
	"github.com/nacos-group/nacos-sdk-go/v2/clients/config_client"
	"github.com/nacos-group/nacos-sdk-go/v2/common/constant"
	"github.com/nacos-group/nacos-sdk-go/v2/vo"
	"gopkg.in/yaml.v2"
	"log"
	"os"
	"strconv"
)

type Config struct {
	Server struct {
		Port      string `yaml:"port"`
		TTSEngine string `yaml:"tts_engine"`
	} `yaml:"server"`

	Database struct {
		Driver   string `yaml:"driver"`
		User     string `yaml:"user"`
		Password string `yaml:"password"`
		Host     string `yaml:"host"`
		Port     string `yaml:"port"`
		Name     string `yaml:"name"`
	} `yaml:"database"`

	Redis struct {
		Model    string   `yaml:"model"`
		Addr     string   `yaml:"addr"`
		Password string   `yaml:"password"`
		DB       int      `yaml:"db"`
		Sentinel sentinel `yaml:"sentinel"`
	} `yaml:"redis"`
}

type sentinel struct {
	MasterName      string   `yaml:"master_name"`
	Password        string   `yaml:"password"`
	SentinelAddress []string `yaml:"sentinel_address"`
	DB              int      `yaml:"db"`
}

var C = &Config{}

func Init(configPath string) {
	if len(configPath) == 0 {
		configPath = "../config/config.yaml"
	}
	yamlFile, err := os.ReadFile(configPath)
	if err != nil {
		log.Fatalf("Failed load config file: %v", err)
	}

	err = yaml.Unmarshal(yamlFile, C)
	if err != nil {
		log.Fatalf("Failed to initialize config: %v", err)
	}
}

func InitServerByNacos() {

	configClient := initNacosClient()
	content, err := configClient.GetConfig(vo.ConfigParam{
		DataId: "tts_cloud_config",
		Group:  "tts_cloud_group",
		Type:   "yaml",
	})
	if err != nil {
		log.Fatalf("load nacos config failed: %v", err)
	}
	err = yaml.Unmarshal([]byte(content), C)
	if err != nil {
		log.Fatalf("Failed to initialize config: %v", err)
	}
}

func initNacosClient() (iClient config_client.IConfigClient) {
	serverIp := os.Getenv("NACOS_SERVER_IP")
	serverPort := os.Getenv("NACOS_SERVER_PORT")
	serverUserName := os.Getenv("NACOS_SERVER_USERNAME")
	serverPassword := os.Getenv("NACOS_SERVER_PASSWORD")
	namespace := os.Getenv("TTS_NACOS_NAMESPACE")
	if len(serverIp) == 0 || len(namespace) == 0 || len(serverPort) == 0 {
		log.Fatal("NACOS_SERVER_ADDR or NACOS_NAMESPACE is not set")
	}
	//端口号转为数值类型
	serverPortUint64, err := strconv.Atoi(serverPort)
	if err != nil {
		log.Fatal("NACOS_SERVER_PORT is not a number")
	}
	// 创建clientConfig
	clientConfig := constant.ClientConfig{
		Username:            serverUserName,
		Password:            serverPassword,
		NamespaceId:         namespace, // 如果需要支持多namespace，我们可以创建多个client,它们有不同的NamespaceId。当namespace是public时，此处填空字符串。
		NotLoadCacheAtStart: true,
		LogDir:              "/tmp/nacos/log",
		CacheDir:            "/tmp/nacos/cache",
	}

	serverConfigs := []constant.ServerConfig{
		{
			IpAddr: serverIp,
			Port:   uint64(serverPortUint64),
		},
	}
	// 创建动态配置客户端的另一种方式 (推荐)
	configClient, err := clients.NewConfigClient(
		vo.NacosClientParam{
			ClientConfig:  &clientConfig,
			ServerConfigs: serverConfigs,
		},
	)
	if err != nil {
		log.Fatal("init nacos client failed")
	}
	return configClient
}
